<template>
  <div
    class="author-avatar-container"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @click="goToAuthorPage"
  >
    <!-- 头像 -->
    <el-avatar :size="size" :src="processedAvatar" class="avatar" @error="handleImageError" />

    <!-- 悬停信息 -->
    <div v-if="showHoverInfo && hoverInfo" class="hover-info">
      <div class="info-item">
        <span class="label">等级</span>
        <span class="value">{{ hoverInfo.level }}</span>
      </div>
      <div class="info-item">
        <span class="label">粉丝</span>
        <span class="value">{{ hoverInfo.fans }}</span>
      </div>
      <div class="info-item">
        <span class="label">关注</span>
        <span class="value">{{ hoverInfo.follow }}</span>
      </div>
      <div class="info-item">
        <span class="label">获赞</span>
        <span class="value">{{ hoverInfo.likes }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

const props = defineProps({
  avatar: {
    type: String,
    required: true
  },
  authorId: {
    type: [String, Number],
    default: null
  },
  size: {
    type: Number,
    default: 100
  },
  showHoverInfo: {
    type: Boolean,
    default: true
  }
});

const router = useRouter();

// 悬停信息
const hoverInfo = ref(null);
const isHovered = ref(false);

// 默认头像列表（从 public/static/faces 目录下随机选择）
const defaultAvatars = [
  '/static/faces/face-1.jpg',
  '/static/faces/face-2.jpg',
  '/static/faces/face-3.jpg',
  '/static/faces/face-4.jpg',
  '/static/faces/face-5.jpg',
  '/static/faces/face-6.jpg',
  '/static/faces/face-7.jpg',
  '/static/faces/face-8.jpg',
  '/static/faces/face-9.jpg',
  '/static/faces/face-10.jpg',
  '/static/faces/face-11.jpg',
  '/static/faces/face-12.jpg',
  '/static/faces/face-13.jpg',
  '/static/faces/face-14.jpg',
  '/static/faces/face-15.jpg',
  '/static/faces/face-16.jpg',
  '/static/faces/face-17.jpg',
  '/static/faces/face-18.jpg',
  '/static/faces/face-19.jpg',
  '/static/faces/face-20.jpg'
];

// 为每个作者ID缓存一个默认头像，确保同一作者的默认头像保持一致
const authorDefaultAvatars = ref(new Map());

// 获取随机的默认头像
const getRandomAvatar = () => {
  const randomIndex = Math.floor(Math.random() * defaultAvatars.length);
  return defaultAvatars[randomIndex];
};

// 为作者获取固定的默认头像
const getAuthorDefaultAvatar = authorId => {
  if (!authorId) {
    return getRandomAvatar();
  }

  // 如果已经有缓存的默认头像，直接返回
  if (authorDefaultAvatars.value.has(authorId)) {
    return authorDefaultAvatars.value.get(authorId);
  }

  // 为该作者生成一个固定的默认头像（基于authorId哈希）
  const hash = hashCode(authorId.toString());
  const avatarIndex = Math.abs(hash) % defaultAvatars.length;
  const selectedAvatar = defaultAvatars[avatarIndex];

  // 缓存这个头像
  authorDefaultAvatars.value.set(authorId, selectedAvatar);

  return selectedAvatar;
};

// 简单的字符串哈希函数
const hashCode = str => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash; // 转换为32位整数
  }
  return hash;
};

// 当前使用的头像URL
const processedAvatar = computed(() => {
  // 如果头像加载失败过，使用错误头像
  if (errorAvatar.value) {
    return errorAvatar.value;
  }

  // 如果没有头像URL，返回默认头像
  if (!props.avatar) {
    return getAuthorDefaultAvatar(props.authorId);
  }

  // 确保 avatar 是字符串
  let avatarUrl = props.avatar;
  if (typeof avatarUrl !== 'string') {
    console.warn('Avatar prop is not a string:', avatarUrl);
    avatarUrl = String(avatarUrl);
  }

  // 检查是否为有效的字符串
  if (!avatarUrl || avatarUrl.trim() === '' || avatarUrl === '[object Object]') {
    return getAuthorDefaultAvatar(props.authorId);
  }

  // 如果是相对路径且不以 / 开头，添加 /
  if (!avatarUrl.startsWith('http') && !avatarUrl.startsWith('/')) {
    avatarUrl = `/${avatarUrl}`;
  }

  // 如果是相对路径（以 / 开头但不是完整的绝对路径），可能需要添加基础路径
  if (
    avatarUrl.startsWith('/') &&
    !avatarUrl.startsWith('/static/') &&
    !avatarUrl.startsWith('/src/')
  ) {
    // 对于看起来像是上传的图片路径，直接使用
    return avatarUrl;
  }

  // 返回处理后的头像URL
  return avatarUrl;
});

// 缓存悬停信息
const hoverInfoCache = new Map();

// 获取悬停信息
const fetchHoverInfo = async () => {
  if (!props.authorId) {
    return;
  }
  if (hoverInfoCache.has(props.authorId)) {
    hoverInfo.value = hoverInfoCache.get(props.authorId);
    return;
  }

  try {
    const response = await fetch(`/api/author/${props.authorId}/hover-info`);
    const data = await response.json();
    hoverInfo.value = data;
    hoverInfoCache.set(props.authorId, data); // 缓存数据
  } catch (error) {
    console.error('Failed to fetch hover info:', error);
  }
};

// 鼠标悬停事件
const handleMouseEnter = () => {
  if (props.showHoverInfo) {
    isHovered.value = true;
    fetchHoverInfo(); // 懒加载悬停信息
  }
};

const handleMouseLeave = () => {
  isHovered.value = false;
};

const errorAvatar = ref(null);
// 处理头像加载失败
const handleImageError = e => {
  console.log('Avatar image load error for:', processedAvatar.value);
  // 头像加载失败时，返回默认头像
  const defaultAvatar = getAuthorDefaultAvatar(props.authorId);
  errorAvatar.value = defaultAvatar;
  // 不直接操作DOM，让Vue的响应式系统处理
};

// 跳转到作者主页
const goToAuthorPage = () => {
  if (!props.authorId) {
    return false;
  }
  try {
    console.log('Navigating to author page:', props.authorId);
    router.push({
      name: 'authorPage',
      params: { authorId: props.authorId }
    });
  } catch (error) {
    console.error('Navigation failed:', error);
  }
};
</script>

<style scoped>
.author-avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar {
  transition: transform 0.3s ease;
}

.author-avatar-container:hover .avatar {
  transform: scale(1.1);
}

.hover-info {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 150px;
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
}

.value {
  color: #333;
  font-weight: bold;
}
</style>
